<script setup>
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  LegendComponent,
  ToolboxComponent,
  BarChart,
  DataZoomComponent
])
import { onBeforeUnmount, onMounted, reactive, watch } from 'vue'
import { typeColors } from '@/utils/config.js'
let chartInstance = null
const props = defineProps(['data', 'eid'])
const option = reactive({
  title: {
    // text: props.title || '',
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '0',
    right: '0',
    bottom: '0',
    containLabel: true
  },
  legend: {
    align: 'left',
    top: 10,
    right: 10,
    itemWidth: 6,
    itemHeight: 6,
    itemGap: 10,
    // 设置图例的样式
    textStyle: {
      color: '#9DA0A4',
      fontSize: 14,
      fontWeight: 400,
      lineHeight: 17,
      fontFamily: 'PingFangSC-Regular',
      letterSpacing: 0
    }
  },
  xAxis: {
    type: 'category',
    axisTick: { show: false }, // 分隔线
    axisLabel: {
      fontSize: 14,
      interval: 0,
      rotate: 30,
      formatter(value) {
        // if (value?.length > 5) {
        //   return splitString(value, 5).join('\n') // 换行
        // }
        return value
      }
    },
    data: []
  },

  yAxis: [
    {
      type: 'value',
      name: '单位（起）',
      nameTextStyle: {
        padding: [0, 0, 0, 30]
      },
      splitLine: { show: false } // 分隔线
    }
  ],
  dataZoom: [
    {
      type: 'slider', // 滑动条类型
      show: false, // 显示滑动条
      xAxisIndex: [0], // 指定 x 轴的索引
      start: 0, // 初始显示的数据范围起点（百分比）
      end: 50 // 初始显示的数据范围终点（百分比）
    },
    {
      type: 'inside', // slider表示有滑动块的，inside表示内置的
      show: true,
      xAxisIndex: [0],
      start: 0,
      end: 50,
      backgroundColor: 'rgba(0,0,0,0.5)', // 滑块背景颜色
      fillerColor: 'rgba(255,255,0,0.5)', // 填充颜色
      showDetail: false // 拖拽时，是否显示详细信息
    }
  ],
  series: [
    {
      name: '敏感',
      type: 'bar',
      barWidth: '30%',
      stack: 'Ad',
      emphasis: {
        focus: 'series'
      },
      data: [],
      itemStyle: {
        color: typeColors.infoSensitive
      }
    },
    {
      name: '一般',
      type: 'bar',
      barWidth: '30%',
      stack: 'Ad',
      emphasis: {
        focus: 'series'
      },
      data: [],
      itemStyle: {
        color: typeColors.infoSensitiveGeneral
      }
    },
    {
      name: '重要',
      type: 'bar',
      barWidth: '30%',
      stack: 'Ad',
      emphasis: {
        focus: 'series'
      },
      data: [],
      itemStyle: {
        color: typeColors.infoSensitiveImportant
      }
    },
    {
      name: '重大',
      type: 'bar',
      barWidth: '30%',
      stack: 'Ad', // 是堆叠还是另外的一个竹子
      emphasis: {
        focus: 'series'
      },
      data: [],
      itemStyle: {
        color: typeColors.infoSensitiveMajor
      }
    }
  ]
})
function splitString(str, len) {
  const result = []
  for (let i = 0; i < str.length; i += len) {
    result.push(str.substring(i, i + len))
  }
  return result
}
onMounted(() => {
  chartInstance = echarts.init(document.getElementById(props.eid))
  props.data.map((item) => {
    option.xAxis.data.push(item.label)
    option.series[0].data.push(item.v1)
    option.series[1].data.push(item.v2)
    option.series[2].data.push(item.v3)
    option.series[3].data.push(item.v4)
  })
  updateChart()
  window.addEventListener('resize', canalDebounce)
})

watch(
  () => props,
  (newVal) => {
    if (newVal.data.length === 0) {
      option.title = {
        text: '暂无数据',
        x: 'center',
        y: 'center',
        textStyle: {
          fontSize: 20,
          fontWeight: 'normal',
          color: 'white'
        }
      }
    } else {
      option.title = {}
    }
    newVal.data.map((item) => {
      option.xAxis.data.push(item.label)
      option.series[0].data.push(item.v1)
      option.series[1].data.push(item.v2)
      option.series[2].data.push(item.v3)
      option.series[3].data.push(item.v4)
    })
    // option.series[0].data =
    updateChart()
  },
  { deep: true }
)

//页面销毁前，销毁事件和实例
onBeforeUnmount(() => {
  window.removeEventListener('resize', canalDebounce)
  // chartInstance.dispose()
})

const updateChart = () => {
  if (chartInstance) {
    chartInstance.setOption(option)
  }
}
const resizeHandler = () => {
  chartInstance.resize()
}
//设置防抖，保证无论拖动窗口大小，只执行一次获取浏览器宽高的方法
const debounce = (fun, delay) => {
  let timer
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fun()
    }, delay)
  }
}
const canalDebounce = debounce(resizeHandler, 500)
</script>

<template>
  <section class="bar-chart-box">
    <div :id="props.eid" style="width: 90%; height: 60vw; z-index: 90" />
  </section>
</template>

<style scoped>
.bar-chart-box {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  margin-bottom: 20px;
  width: 100%;
  padding: 0;
}
</style>
